package linear_list.leetcode.easy;

/**
 * @author Stark
 * @description 移除链表元素
 * 题目链接：https://leetcode-cn.com/problems/remove-linked-list-elements
 * @date 2022/4/10 23:38
 **/
public class Num203_RemoveElements {
    int choice = 1;
    public ListNode removeElements(ListNode head, int val) {
        if(choice == 1){
            //非递归法
            if(head == null)
                return head;
            ListNode dummyHead = new ListNode(0,head);
            //next用来判断当前结点和val是否相同
            //cur用于跳过删除结点
            ListNode cur = dummyHead,next = dummyHead.next;
            while(next != null){
                if(next.val == val)
                    //跳过该结点
                    cur.next = next.next;
                else
                    //保留结点,往后移动
                    cur = cur.next;
                //往后遍历
                next = next.next;
            }
            return dummyHead.next;
        }else if(choice == 2){
            //递归法
            if(head == null)
                return head;
            if(head.val == val){
                //不进行拼接操作,接收下一个不等于val的结点
                head = removeElements(head.next,val);
            }else{
                //拼接操作,并返回当前和val不相等的结点
                head.next = removeElements(head.next,val);
            }
            return head;
        }
        return null;
    }
}
